package edu.xidian.onlinedocument.controller;

import edu.xidian.onlinedocument.handler.excpetions.CustomExceptionHandler;
import edu.xidian.onlinedocument.handler.excpetions.custom.CustomException;
import edu.xidian.onlinedocument.handler.interceptor.TokenCheck;
import edu.xidian.onlinedocument.views.*;
import edu.xidian.onlinedocument.entity.*;
import edu.xidian.onlinedocument.views.elder.UserTokenMapper;
import edu.xidian.onlinedocument.views.groups.*;
import edu.xidian.onlinedocument.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestControllerAdvice
@RestController
@RequestMapping("/api/users")
@CrossOrigin(originPatterns = "*",
        methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT}) // 跨域解决方案
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService){
        this.userService = userService;
    }

    @GetMapping(value = "/test")
    // @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Result getUsers(){
        List<UserData> userData = userService.getAllUsersData();
        return new CustomExceptionHandler<>().sendSuccessResponse(userData);
    }

    @GetMapping(value = "/test/{num}", produces = "application/json")
    // @RequestMapping(value = "/test/{num}", method = RequestMethod.GET, produces = "application/json")
    public Result getOneUser(@RequestBody UserData info) {
        UserTokenMapper token = new UserTokenMapper(info.getUserNum());
        if(!userService.isExistUser(info.getUserNum())){
            throw new CustomException(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        return new CustomExceptionHandler<UserTokenMapper>().sendSuccessResponse(token);
    }

    /**
     * 获取全部用户信息以及其创建的文档（测试用）
     * @return Result
     */
    @GetMapping(value = "/documents/test/creator")
    public Result getAllUserInfoAndDocumentList() {
        List<UserData> data = userService.getAllUserInfoAndDocumentList();
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 获取全部用户信息以及其编辑的文档（测试用）
     * @return Result
     */
    @GetMapping(value = "/documents/test/editor")
    public Result getAllUserInfoAndEditorList() {
        List<UserData> data = userService.getAllUserInfoAndEditorList();
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 获取全部用户信息以及其创建的文档和编辑的文档（测试用）
     * @return Result
     */
    @GetMapping(value = "/documents/test/creator-and-editor")
    public Result getAllUserInfoAndDocumentListAndEditorList() {
        List<UserData> data = userService.getAllUserInfoAndDocumentListAndEditorList();
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 注册功能
     * @param info 注册信息
     * @return Result
     */
    @PostMapping(produces = "application/json")
    public Result register(@RequestBody @Validated({DataGroupA.class, DataGroupB.class, DataGroupC.class})
                                       UserData info) {
        userService.register(info.getUserName(), info.getUserNum(), info.getUserKey());
        return new CustomExceptionHandler<>().sendSuccessResponse();
    }

    /**
     * 登录功能
     * @param info 登陆信息
     * @param userNum 用户账号
     * @return Result
     */
    @PostMapping(value = "/{userNum}", produces = "application/json")
    public Result login(@RequestBody @Validated({DataGroupB.class}) UserData info,
                        @PathVariable("userNum") String userNum){
        String token = userService.login(info.getUserNum(), info.getUserKey());
        if(token == null){
            throw new CustomException(ResultCode.LOGIN_FAILED);
        }
        UserTokenData userTokenData = new UserTokenData();
        userTokenData.setUserToken(token);
        return new CustomExceptionHandler<>().sendSuccessResponse(userTokenData);
    }

    /**
     * 注销功能
     * @param userNum 用户账号
     * @return Result
     */
    @DeleteMapping(value = "/{userNum}", produces = "application/json")
    @TokenCheck
    public Result logout(/*@RequestBody @Validated({DataGroupA.class}) Request request,*/
                         @PathVariable("userNum") String userNum){
        // JSON.paresObject方法为com.alibaba.fastjson.JSON包中的方法，将map转换为自定义类
        // 其中JSON格式文件直接读取就是以Map类型数组形式存储
        // UserData userData = JSON.parseObject(JSON.toJSONString(request.getData()), UserData.class);
        userService.logout(userNum);
        return new CustomExceptionHandler<>().sendSuccessResponse();
    }

    /**
     * 根据账号获取用户信息
     * @param userNum 账号
     * @return Result
     */
    @GetMapping(value = "/{userNum}")
    @TokenCheck
    public Result getUserInfo(@PathVariable("userNum") String userNum) {
        UserData data = userService.getOneUserInfoByUserNum(userNum);
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 根据账号获取用户昵称
     * @param userNum 账号
     * @return Result
     */
    @GetMapping(value = "/{userNum}/name")
    @TokenCheck
    public Result getUserName(@PathVariable("userNum") String userNum) {
        UserData data = userService.getOneUserNameByUserNum(userNum);
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 根据账号获取用户信息以及其创建的文档
     * @param userNum 账号
     * @return Result
     */
    @GetMapping(value = "/{userNum}/documents/creators")
    @TokenCheck
    public Result getUserInfoAndDocumentList(@PathVariable("userNum") String userNum) {
        UserData data = userService.getOneUserInfoAndDocumentList(userNum);
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 根据账号获取用户信息以及其编辑的文档
     * @param userNum 账号
     * @return Result
     */
    @GetMapping(value = "/{userNum}/documents/editors")
    @TokenCheck
    public Result getUserInfoAndEditorList(@PathVariable("userNum") String userNum) {
        UserData data = userService.getOneUserInfoAndEditorList(userNum);
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }

    /**
     * 根据账号获取用户信息以及其创建和编辑的文档
     * @param userNum 账号
     * @return Result
     */
    @GetMapping(value = "/{userNum}/documents/creators-and-editors")
    @TokenCheck
    public Result getUserInfoAndDocumentListAndEditorList(@PathVariable("userNum") String userNum) {
        UserData data = userService.getOneUserInfoAndDocumentListAndEditorList(userNum);
        return new CustomExceptionHandler<>().sendSuccessResponse(data);
    }
}
